import { defineStore } from 'pinia';
import { aiApi } from '@/services/api';
import { useConfigStore } from './config';

export const useAiStore = defineStore('ai', {
  state: () => ({
    conversations: [],
    loading: false,
    error: null
  }),
  actions: {
    async runRagQuery(payload) {
      this.loading = true;
      this.error = null;
      const config = useConfigStore();
      config.loadFromStorage();
      try {
        const response = await aiApi.rag({
          headers: config.authHeaders,
          data: {
            query: payload.query,
            topK: payload.topK ?? config.topK,
            temperature: payload.temperature ?? config.temperature,
            provider: payload.provider ?? config.embeddingsProvider,
            includeMetadata: payload.includeMetadata ?? true
          }
        });
        const id = typeof crypto !== 'undefined' && crypto.randomUUID
          ? crypto.randomUUID()
          : `ai-${Date.now()}-${Math.random().toString(16).slice(2)}`;
        this.conversations.unshift({
          id,
          timestamp: Date.now(),
          request: payload,
          response
        });
        return response;
      } catch (error) {
        this.error = error;
        throw error;
      } finally {
        this.loading = false;
      }
    },
    clearHistory() {
      this.conversations = [];
    }
  }
});
